package com.atxyj.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atxyj.srb.core.listener.ExcelDictDtoListener;
import com.atxyj.srb.core.pojo.dto.ExcelDictDto;
import com.atxyj.srb.core.pojo.entity.Dict;
import com.atxyj.srb.core.mapper.DictMapper;
import com.atxyj.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author xyj
 * @since 2021-04-27
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private RedisTemplate redisTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDto.class, new ExcelDictDtoListener(baseMapper)).sheet().doRead();
        log.info("数据导入成功！");
    }

    @Override
    public List<ExcelDictDto> listDictData() {
        List<Dict> dictList = baseMapper.selectList(null);
        //创建ExcelDictDto列表，将Dict列表转换成ExcelDictDto列表
        List<ExcelDictDto> excelDictDtoList = new ArrayList<>(dictList.size());
        dictList.forEach(dict -> {
            ExcelDictDto excelDictDto = new ExcelDictDto();
            BeanUtils.copyProperties(dict,excelDictDto);
            excelDictDtoList.add(excelDictDto);
        });
        return excelDictDtoList;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {



        try {
            //首先查询redis中是否存在数据列表
            List<Dict> dictList =  (List<Dict>)redisTemplate.opsForValue().get("srb:core:dictList" + parentId);

            //如果存在则从redis中直接返回数据列表
            if(dictList != null) {
                log.info("从redis中取出数据");
                return dictList;
            }

        } catch (Exception e) {
            //对这里处理异常的原因是，如果没有处理异常的话，那么就直接把异常抛出去了，不会再去查数据库。而这里处理异常
            //即使因为某种原因redis出现异常，也能从数据库中查询数据。这里使用redis只是为了提高效率
            //将错误跟踪栈的异常打印到日志里面
          log.error("redis服务器异常:" + ExceptionUtils.getStackTrace(e));
        }
        //如果不存在则查询数据库
            log.info("从数据库中获取数据列表");
            QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
            dictQueryWrapper.eq("parent_id", parentId);
            List<Dict>  dictList = baseMapper.selectList(dictQueryWrapper);
            //填充hasChildren字段
            dictList.forEach(dict -> {
                //判断当前节点是否有子节点
                boolean hasChildren = this.hasChildren(dict.getId());
                dict.setHasChildren(hasChildren);
            });


        try {
            //将数据存入redis
            log.info("将数据存入redis中");
            redisTemplate.opsForValue().set("srb:core:dictList" + parentId,dictList,5 , TimeUnit.MINUTES);

        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回数据
        return dictList;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code" , dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);

        return this.listByParentId(dict.getId());
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {

        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("dict_code" , dictCode);
        //通过dict_code获取一个下拉列表下所有选型
        Dict parentDict = baseMapper.selectOne(queryWrapper);
        if( parentDict == null) {
            return  "";
        }
        queryWrapper =  new QueryWrapper<>();
        //通过dictId和value获取名称
        queryWrapper.eq("parent_id", parentDict.getId()).eq("value", value);
        Dict dict = baseMapper.selectOne(queryWrapper);
        if(dict == null ) {
            return "";
        }
        return dict.getName();
    }

    /**
     * 判断当前id所在的节点下是否有子节点
     * @param id
     * @return
     */
    private boolean hasChildren(Long id) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(dictQueryWrapper);
        if(count.intValue() > 0) {
            return true;
        }
            return false;


    }

}
